<template>
  <!-- 商品分类组件 -->
  <div class="goods-category">
    <!-- 头部路径导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 商品分类列表数据 -->
    <el-card class="box-card">
      <el-button type="primary" size="default" @click="addCategory"
        >添加分类</el-button
      >
      <div class="goods-cat-table">
        <el-table
          :data="categoryList"
          border
          style="width: 100%"
          row-key="cat_id"
          :tree-props="{ children: 'children' }"
        >
          <el-table-column prop="index" label="#" width="48" type="">
          </el-table-column>
          <el-table-column prop="cat_name" label="分类名称"> </el-table-column>
          <el-table-column label="是否有效">
            <template slot-scope="props">
              <i
                class="el-icon-success"
                style="color: #67c23a"
                v-if="props.row.cat_deleted == false"
              ></i>
              <i
                class="el-icon-error"
                style="color: #f56c6c"
                v-if="props.row.cat_deleted == true"
              ></i>
            </template>
          </el-table-column>
          <el-table-column label="排序">
            <template slot-scope="props">
              <el-tag v-if="props.row.cat_level == 0" size="mini">一级</el-tag>
              <el-tag type="success" v-if="props.row.cat_level == 1" size="mini"
                >二级</el-tag
              >
              <el-tag type="warning" v-if="props.row.cat_level == 2" size="mini"
                >三级</el-tag
              >
            </template>
          </el-table-column>

          <el-table-column label="排序">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="editCategory(scope.row.cat_id)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="deleteCategory(scope.row.cat_id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageConfig.currentPage"
          :page-sizes="pageConfig.pageSizes"
          :page-size="pageConfig.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageConfig.pageTotal"
          :hide-on-single-page="false"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 修改分类弹出层 -->
    <el-dialog
      title="修改分类"
      :visible.sync="dialogEditCatVisible"
      class="edit-cat-dialog"
    >
      <el-form
        :model="editCatForm"
        :rules="editCatFormRules"
        ref="editCatForm"
        class="demo-ruleForm"
        :label-position="'left'"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="catName">
          <el-input v-model="editCatForm.catName"></el-input>
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-button @click="dialogEditCatVisible = false">取消</el-button>
          <el-button type="primary" @click="editCatSubmit('editCatForm')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 添加分类弹出层 -->
    <el-dialog
      title="添加商品分类"
      :visible.sync="dialogAddCatVisible"
      class="add-cat-dialog"
    >
      <el-form
        :model="addCatForm"
        :rules="editCatFormRules"
        ref="addCatForm"
        class="demo-ruleForm"
        :label-position="'right'"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="catName">
          <el-input v-model="addCatForm.catName"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            :options="addCatForm.catList"
            :props="addCatForm.casProps"
            ref="addCatCascader"
            clearable
            style="width: 100%"
            popper-class="cat-cascader"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-button @click="dialogAddCatVisible = false">取消</el-button>
          <el-button type="primary" @click="addCatSubmit('addCatForm')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //商品分类列表数据
      categoryList: [],
      //控制添加分类弹出层显示
      dialogAddCatVisible: false,
      //控制修改分类弹出层显示
      dialogEditCatVisible: false,
      //加载层参数配置
      loadingConfig: {
        target: "body",
        fullscreen: true,
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.1)",
        text: "拼命加载中",
      },
      //分页器参数配置
      pageConfig: {
        pageTotal: 0, //分页器总条数
        pageSize: 5, //每页显示条数
        pageSizes: [5, 10, 15, 20], //可选择的每页条数
        currentPage: 1, //分页器当前页码
      },
      //修改分类数据
      editCatForm: {
        editCatId: null,
        catName: "",
      },
      //修改分类表单验证规则
      editCatFormRules: {
        catName: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "分类名称长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
      //添加分类表单数据
      addCatForm: {
        catName: "",
        catList: [],
        //级联菜单属性
        casProps: {
          expandTrigger: "hover",
          checkStrictly: true,
          value: "cat_id",
          label: "cat_name",
        },
        catPid: 0,
        catLevel: 0,
      },
    };
  },
  methods: {
    getCategoryList() {
      //获取商品分类列表
      //打开加载层
      var loading = this.$loading.service(this.loadingConfig);
      //发起请求
      this.$axios
        .get("/categories", {
          params: {
            type: [1, 2, 3],
            pagenum: this.pageConfig.currentPage,
            pagesize: this.pageConfig.pageSize,
          }
        })
        .then((res) => {
          if (res.meta.status == 200) {
            //给每个第一级添加序号
            res.data.result.forEach((item, index) => {
              item["index"] = index + 1;
            });
            //设置分类列表数据
            this.categoryList = res.data.result;
            //设置分页器总条数
            this.pageConfig.pageTotal = res.data.total;
            //设置当前页
            this.pageConfig.currentPage = res.data.pagenum + 1;
            //判断当前页是否为空
            if ((this.pageConfig.currentPage - 1)  * this.pageConfig.pageSize == this.pageConfig.pageTotal) {
                if (this.pageConfig.currentPage  - 1 < 1) {
                    this.handleCurrentChange(1);
                } else {
                    this.handleCurrentChange(this.pageConfig.currentPage - 1);
                }  
            }
          } else {
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          this.$message.error(error);
        })
        .finally(() => {
          //关闭加载层
          this.$nextTick(() => {
            loading.close();
          });
        });
    },
    editCategory(id) {
      //设置正在编辑的分类ID
      this.editCatForm.editCatId = id;
      //查询待编辑分类的信息
      this.getCatInfo(id, () => {
        //打开编辑窗
        this.dialogEditCatVisible = true;
      });
    },
    editCatSubmit(formName) {
      //修改分类提交
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //打开加载层
          var loading = this.$loading.service(this.loadingConfig);
          //发起请求
          this.$axios
            .put("/categories/" + this.editCatForm.editCatId, {
              cat_name: this.editCatForm.catName,
            })
            .then((res) => {
              if (res.meta.status == 200) {
                //提示成功信息
                this.$message.success(res.meta.msg);
                //关闭弹出层
                this.dialogEditCatVisible = false;
                //刷新数据
                this.getCategoryList();
              } else {
                //提示错误信息
                this.$message.error(res.meta.msg);
              }
            })
            .catch((error) => {
              this.$message.error(error);
            })
            .finally(() => {
              //关闭加载层
              this.$nextTick(() => {
                loading.close();
              });
            });
        }
      });
    },
    deleteCategory(id) {
      //删除商品分类
      //调用确认弹框
      this.$confirm("此操作将永久删除该分类，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //点击确定执行删除商品
        this.deleteCategorySubmit(id);
      });
    },
    deleteCategorySubmit(id) {
      //删除商品提交
      //打开加载层
      var loading = this.$loading.service(this.loadingConfig);
      //发起请求
      this.$axios
        .delete("/categories/" + id)
        .then((res) => {
          if (res.meta.status == 200) {
            //提示成功信息
            this.$message.success(res.meta.msg);
            //重新刷新数据
            this.getCategoryList();
            
            console.log(this.pageConfig.currentPage);
          } else {
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          this.$message.error(error);
        })
        .finally(() => {
          //关闭加载层
          this.$nextTick(() => {
            loading.close();
          });
        });
    },
    addCategory() {
      //重置添加分类表单数据
      this.addCatForm.catName = "";
      this.addCatForm.catLevel = 0;
      this.addCatForm.catPid = 0;

      //获取商品分类
      //打开加载层
      var loading = this.$loading.service(this.loadingConfig);
      //发起请求
      this.$axios
        .get("/categories")
        .then((res) => {
          if (res.meta.status == 200) {
            //处理数据，去除最后一级
            function filterData(arr) {
              for (var i = 0; i < arr.length; i++) {
                if (arr[i].cat_level == 0 && arr[i].children) {
                  for (var j = 0; j < arr[i].children.length; j++) {
                    if (
                      arr[i].children[j].cat_level == 1 &&
                      arr[i].children[j].children
                    ) {
                      delete arr[i].children[j].children;
                    }
                  }
                }
              }
              return arr;
            }
            //设置分类列表数据
            this.addCatForm.catList = filterData(res.data);
            //打开添加商品分类的弹出层
            this.dialogAddCatVisible = true;
            //重置选择器内容
            if (this.$refs["addCatCascader"]) {
              this.$refs["addCatCascader"].handleClear();
            }
          } else {
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          this.$message.error(error);
        })
        .finally(() => {
          //关闭加载层
          this.$nextTick(() => {
            loading.close();
          });
        });
    },
    addCatSubmit(formName) {
      //添加商品分类提交
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //打开加载层
          var loading = this.$loading.service(this.loadingConfig);
          //更新提交的数据
          if (this.$refs["addCatCascader"]) {
            if (this.$refs["addCatCascader"].getCheckedNodes(true).length > 0) {
              //更新选中的分类ID
              this.addCatForm.catPid = this.$refs[
                "addCatCascader"
              ].getCheckedNodes(true)[0].data.cat_id;
              //更新层级
              this.addCatForm.catLevel =
                this.$refs["addCatCascader"].getCheckedNodes(true)[0].data
                  .cat_level + 1;
            }
          }
          //发起请求
          this.$axios
            .post("/categories", {
              cat_pid: this.addCatForm.catPid,
              cat_name: this.addCatForm.catName,
              cat_level: this.addCatForm.catLevel,
            })
            .then((res) => {
              if (res.meta.status == 201) {
                //提示成功信息
                this.$message.success(res.meta.msg);
                //关闭弹出层
                this.dialogAddCatVisible = false;
                //重新刷新数据
                this.getCategoryList();
              } else {
                //提示错误信息
                this.$message.error(res.meta.msg);
              }
            })
            .catch((error) => {
              this.$message.error(error);
            })
            .finally(() => {
              //关闭加载层
              this.$nextTick(() => {
                loading.close();
              });
            });
        }
      });
    },
    getCatInfo(id, cb) {
      //根据ID查询分类
      //打开加载层
      var loading = this.$loading.service(this.loadingConfig);
      //发起请求
      this.$axios
        .get("/categories/" + id)
        .then((res) => {
          if (res.meta.status == 200) {
            //设置正在编辑的分类名称
            this.editCatForm.catName = res.data.cat_name;
            //执行回调函数
            if (cb) {
              cb();
            }
          } else {
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          this.$message.error(error);
        })
        .finally(() => {
          //关闭加载层
          this.$nextTick(() => {
            loading.close();
          });
        });
    },
    handleSizeChange(val) {
      //切换每页条数重新获取用户数据
      this.pageConfig.pageSize = val;
      this.getCategoryList();
    },
    handleCurrentChange(val) {
      //切换页码时重新获取用户数据
      this.pageConfig.currentPage = val;
      this.getCategoryList();
    },
  },
  mounted() {
    //模板加载完成后渲染数据
    this.getCategoryList();
  },
};
</script>

<style lang="less">
.goods-cat-table {
  margin-top: 15px;
}
.el-cascader-menu__wrap {
  height: 300px !important;
}
</style>